package com.zwps.common.api.validator;

import java.lang.reflect.Method;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.zwps.common.tool.enums.InterfaceEnum;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义枚举选项校验器
 * 
 * @ClassName: EnumOptionValidator
 * @Description:
 * @author
 * @date 2023年5月23日 上午11:36:40
 *
 */
@Slf4j
public class EnumOptionValidator implements ConstraintValidator<EnumOption, Object> {

    private InterfaceEnum<?>[] options;

    @Override
    public void initialize(EnumOption enumOption) {
        Method method;
        try {
            Class<? extends InterfaceEnum<?>> value = enumOption.value();
            method = enumOption.value().getMethod("values");
            if (method == null) {
                log.error("Option class is not Enum, class: {}", value);
                // 不存在values方法表示不是枚举类
                throw new RuntimeException("参数校验错误");
            }
            Object obj = method.invoke(null);
            if (!(obj instanceof InterfaceEnum[])) {
                log.error("Option class is not InterfaceEnum implement, class: {}", value);
                throw new RuntimeException("参数校验错误.");
            }
            options = (InterfaceEnum[]) obj;
        } catch (Exception e) {
            log.error("EnumOptionValidator isinitialize error: ", e);
            throw new RuntimeException("参数校验错误.");
        }

    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (ObjectUtil.isEmpty(value)) {
            return true;
        }
        if (options == null || options.length == 0) {
            return false;
        }
        for (InterfaceEnum<?> interfaceEnum : options) {
            Object code = interfaceEnum.getCode();
            if (code != null && ObjectUtil.equal(value, code)) {
                return true;
            }
        }
        return false;
    }
}
